package com.example.teamtribe.main.club;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.model.FileModel;
import com.example.teamtribe.database.Team;

import java.util.ArrayList;
import java.util.List;

public class ClubPresenter implements ClubContract.Presenter {

    private ClubContract.View view;
    private ClubModel model;

    public ClubPresenter(ClubContract.View view) {
        this.view = view;
        model = new ClubModel();
    }

    @Override
    public void start(int schoolId) {
        if (schoolId == 0) {
            view.toCertify(true);
        } else {
            view.toCertify(false);
            List<Team> teams = model.getLocalTeams(schoolId);
            for(Team t:teams){
            }
            if (teams == null || teams.isEmpty()) {
                getTeams(schoolId);
            } else {
                view.clearTeams();
                view.addTeams(teams);
                view.finishRefresh();
            }
        }
    }

    @Override
    public void getTeams(int schoolId) {
        model.getTeamIds(schoolId, 0, new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                ArrayList<Integer> ids = bundle.getIntegerArrayList("ids");
                model.clearLocalTeams();
                view.clearTeams();
                for (int i = 0; i < ids.size(); i++) {
                    getTeam(ids.get(i));
                    if (i == ids.size() - 1){
                        view.finishRefresh();
                    }
                }
            }

            @Override
            public void failure(String meg) {
                view.finishRefresh();
                view.showToast(meg);
            }
        });
    }

    @Override
    public void getTeam(int teamId) {
        model.getTeam(teamId, new FileModel.FileBack() {
            @Override
            public void loadSuccess(String fileName) {
                view.setPortrait();
            }

            @Override
            public void success(@Nullable Bundle bundle) {
                Team team = bundle.getParcelable("team");
                team.saveOrUpdate();
                view.addTeam(team);
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
                view.finishRefresh();
            }
        });
    }
}
